package com.tencent.sr.iris.basic.saas.service.group;

import com.alibaba.fastjson.JSON;
import com.tencent.sr.iris.activity.interfaces.request.group.AdvisorGroupTaskRequest;
import com.tencent.sr.iris.activity.interfaces.request.operate.OperateBoardRequest;
import com.tencent.sr.iris.activity.interfaces.request.operate.OperateBoardThirdRequest;
import com.tencent.sr.iris.activity.interfaces.request.operate.UnJoinTaskRequest;
import com.tencent.sr.iris.baisc.saas.export.sdk.TaskDependency;
import com.tencent.sr.iris.basic.saas.common.enums.YesOrNoEnum;
import com.tencent.sr.iris.basic.saas.common.exception.BizErrorCode;
import com.tencent.sr.iris.basic.saas.common.exception.TaskBrokerErrorCode;
import com.tencent.sr.iris.basic.saas.common.utils.AssertUtils;
import com.tencent.sr.iris.basic.saas.common.utils.BizUtil;
import com.tencent.sr.iris.basic.saas.interfaces.response.export.ExportResponse;
import com.tencent.sr.iris.user.core.service.interfaces.client.user.IrisUserInfoClient;
import com.tencent.sr.iris.user.core.service.interfaces.dto.IrisUserInfoDTO;
import com.tencent.sr.iris.user.core.service.interfaces.enums.StaffFromTypeEnum;
import com.tencent.sr.iris.user.core.service.interfaces.request.user.UserInfoQueryRequest;
import com.tencent.sr.iris.user.core.service.interfaces.response.user.UserInfoQueryResponse;
import com.tencent.sr.rmall.common.primitive.HttpResult;
import com.tencent.sr.rmall.material.interfaces.enums.ETaskBusinessType;
import com.tencent.sr.rmall.material.interfaces.enums.ETaskStatus;
import com.tencent.sr.rmall.material.interfaces.enums.ETaskType;
import com.tencent.sr.rmall.material.interfaces.request.AddTaskRecordRequest;
import com.tencent.sr.rmall.springbootstarter.authtoken.localbean.AppUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

@Service
@Slf4j
public class ExportOperateService {
    @Resource
    private AppUser appUser;

    @Resource
    private TaskDependency taskDependency;
    
    @Resource
    private IrisUserInfoClient irisUserInfoClient;

    /**
     * 运营平台--一级页面导出
     *
     * @param request
     * @return
     */
    public ExportResponse operateBoard(AdvisorGroupTaskRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_BOARD, request);
    }
    /**
     * 运营平台--邀新有礼导出-二级页面
     *
     * @param request
     * @return
     */
    public ExportResponse operateInviteBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_INVITE, request);
    }

    /**
     * 运营平台--(GMV冲刺赛/销量冲刺赛)导出-二级页面
     *
     * @param request
     * @return
     */
    public ExportResponse operateSprintBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_SPRINT, request);
    }

    /**
     * 运营平台--佣金回滚任务导出-二级页面
     *
     * @param request
     * @return
     */
    public ExportResponse operateCommissionBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_COMMISSION, request);
    }

    public ExportResponse operateFirstOrderBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_FIRST_ORDER, request);
    }

    public ExportResponse operateNormalBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_NORMAL_INVITE, request);
    }

    public ExportResponse operateSpecialBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_SPECIAL_INVITE, request);
    }
    
    public ExportResponse operateNormalBoardThird(OperateBoardThirdRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_NORMAL_INVITE_THIRD, request);
    }
    
    public ExportResponse operateSpecialBoardThird(OperateBoardThirdRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_SPECIAL_INVITE_THIRD, request);
    }

    /**
     * 导师-二级页(排行榜)
     * @param request
     * @return
     */
    public ExportResponse operateRankBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_RANK, request);
    }

    /**
     * 导师-三级页(排行榜)
     * @param request
     * @return
     */
    public ExportResponse operateRankBoardThird(OperateBoardThirdRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_RANK_THIRD, request);
    }

    /**
     * 导师-二级页(排行榜)
     * @param request
     * @return
     */
    public ExportResponse operateSpecialSprintBoard(OperateBoardRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_SPECIAL_SPRINT, request);
    }

    /**
     * 导师-三级页(排行榜)
     * @param request
     * @return
     */
    public ExportResponse operateSpecialSprintBoardThird(OperateBoardThirdRequest request) {
        return commonOperateRequest(ETaskBusinessType.IRIS_OPERATE_SPECIAL_SPRINT_THIRD, request);
    }


    public ExportResponse unJoinTask(UnJoinTaskRequest request) {
        Integer isAdviser = request.getIsAdviser();
        if (checkAdvisor(isAdviser)) {
            request.setUserTutorUid(appUser.getUid());
        }
        return commonOperateRequest(ETaskBusinessType.IRIS_UNJOIN_TASK_GROUP, request);
    }

    /**
     * 校验导师身份
     * @param isAdvisor
     */
    private boolean checkAdvisor(Integer isAdvisor) {
        if (Objects.equals(isAdvisor, YesOrNoEnum.YES.getValue())) {
            UserInfoQueryRequest request = new UserInfoQueryRequest();
            request.setUid(appUser.getUid());
            HttpResult<UserInfoQueryResponse> response = irisUserInfoClient.queryUserInfo(request);
            
            AssertUtils.isNotNull(response, BizErrorCode.RPC_ERROR);

            UserInfoQueryResponse queryResponse = response.getData();
            AssertUtils.isNotNull(queryResponse, TaskBrokerErrorCode.CHECK_ADVISOR_IDENTITY);

            IrisUserInfoDTO userInfoDTO = Optional.ofNullable(queryResponse.getUserInfoDTO())
                    .orElseGet(IrisUserInfoDTO::new);
            AssertUtils.isNotNull(userInfoDTO.getType(), TaskBrokerErrorCode.CHECK_ADVISOR_IDENTITY);

            Integer type = Integer.valueOf(userInfoDTO.getType());
            boolean advisor = Objects.equals(String.valueOf(type), StaffFromTypeEnum.TUTOR.getCode());
            AssertUtils.isTrue(advisor, TaskBrokerErrorCode.CHECK_ADVISOR_IDENTITY);
            
            return true;
        }
        
        return false;
    }


    public <T> ExportResponse commonOperateRequest(ETaskBusinessType eTaskBusinessType, T t) {
        Long rootSaasId = BizUtil.getRootSaasId(appUser);
        String uid = BizUtil.getUid(appUser);
        AddTaskRecordRequest addTaskRecordRequest = new AddTaskRecordRequest();
        addTaskRecordRequest.setSaasId(rootSaasId);
        addTaskRecordRequest.setOperatorId(uid);
        addTaskRecordRequest.setTaskStatus(ETaskStatus.WAIT.getStatus());
        addTaskRecordRequest.setTaskType(ETaskType.EXPORT.getType());
        addTaskRecordRequest.setRequestParam(JSON.toJSONString(t));
        log.info(eTaskBusinessType.getDesc() + "请求参数:{}", addTaskRecordRequest.getRequestParam());
        addTaskRecordRequest.setBusinessType(eTaskBusinessType.getStatus());
        addTaskRecordRequest.setReportFormName(genName(eTaskBusinessType));
        Long taskId = taskDependency.addTask(addTaskRecordRequest);
        ExportResponse exportTaskResponse = new ExportResponse();
        exportTaskResponse.setFileName(addTaskRecordRequest.getReportFormName());
        exportTaskResponse.setTaskId(taskId);
        log.info("commonOperateRequest export response:{}", JSON.toJSONString(exportTaskResponse));
        return exportTaskResponse;
    }


    private String genName(ETaskBusinessType t) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
        String formatStr = formatter.format(new Date());
        return t.getDesc() + "-" + formatStr + ".xlsx";
    }

}
